<script setup lang="ts">
import { transformDataToKeys } from '@/utils';
import { generateNameToLevel } from '@/config/constant';
import { Message } from '@/instance';
import { modalMaterialConfig } from './config/table-config';
import { saveSuccess } from '@/components/base-ui/base-table/hooks/useTableAction';
import {
    doGetMaterialSetting,
    doEditMaterialSetting,
    doAddMaterialSetting,
    doDelMaterialSetting
} from '@/api/base/materialsManagement';
import type { MaterialSetting } from '@/api/base/materialsManagement/model/type';

/**
 * 成功获取表格数据
 */
const handleLoadData = () => {
    const tableData: MaterialSetting[] = modalSlotRef.value.tableData;
    const AddOptionsLen = tableData.filter(item => item.edit).length;

    if (!AddOptionsLen) modalSlotRef.value.add();

    filterAndInsert(tableData);
};

/**
 * 三个固定分类，分别为“原材料、半成品、成品”这三个分类前期展示在物料分类设置弹窗中的1、2、3顺序中，置灰，不可勾选操作删除和编辑。
 */
const filterAndInsert = (data: MaterialSetting[]) => {
    const arr = ['成品', '半成品', '原材料'];

    arr.forEach((item: any) => {
        const index = data.findIndex(function (obj) {
            return obj.classificationName === item;
        });

        if (index > -1) {
            const element = data.splice(index, 1)[0];
            element.disabled = true;
            data.unshift(element);
        }
    });
};

// 禁用表格操作权限
const handleDisabled = (row: MaterialSetting) => row.disabled!;

/**
 * 新增/编辑
 */
const { modalOk, modalSlotRef, getMaxHeight } = useModal();

// const { search } = useParams(modalSlotRef);

/**
 * 物料分类设置行内编辑保存
 */
const { rowEdit } = useEditRow(modalSlotRef, doEditMaterialSetting);
const handleMaterialChange = async (row: any, oldRow: any) => {
    try {
        const data = transformDataToKeys<MaterialSetting>(row, [
            'id',
            'classificationName',
            'description'
        ]);
        const res = await rowEdit<MaterialSetting>(data, oldRow);
        if (!res) return;
        // 将最新数据替换备份数据
        saveSuccess(row, oldRow, modalSlotRef);
    } catch (error) {
        console.log('error', error);
    }
};

// 删除数据
const selectIds = ref<number[]>([]);
const handleSelection = (list: MaterialSetting[]) => {
    selectIds.value = list.map((item: MaterialSetting) => item.id!);
};

const { rowDel } = useDelRow(modalSlotRef, selectIds, doDelMaterialSetting);

/**
 * 物料分类确认新增
 */
const getData = async () => {
    let data: MaterialSetting[] = modalSlotRef.value.getSaveData();
    await doAddMaterialSetting(data);
    Message.success('操作成功！');
    modalSlotRef.value?.getData?.();
};

const handleOk = () => {
    modalOk(getData);
};

const handleSelectDisabled = (row: MaterialSetting) => {
    return !row.disabled;
};

defineExpose({
    handleOk
});
</script>

<template>
    <div style="padding: 0 10px">
        <base-table
            :id="generateNameToLevel('1')"
            ref="modalSlotRef"
            valid-popover-position="left"
            :getDataFn="doGetMaterialSetting"
            :max-height="getMaxHeight"
            :add-table-row="true"
            :cell-edit="true"
            :tableConfig="modalMaterialConfig"
            :modal-mode="true"
            :editDisabledFn="handleDisabled"
            :delDisabledFn="handleDisabled"
            :selectable="handleSelectDisabled"
            @change="handleMaterialChange"
            @selectionChange="handleSelection"
            @del="rowDel"
            @load="handleLoadData"
        >
        </base-table>
    </div>
</template>

<style lang="scss" scoped></style>
